/* 
**  File: getproj.c
**
**  This file is part of the AQUA program suite, which is being
**  developed in the NMR Spectroscopy Department, Bijvoet Center for 
**  Biomolecular Research, Utrecht. 
**
**
**  AUTHOR(S) : Ton Rullmann
**  DATE      : July 17, 1995
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define FALSE      0
#define TRUE       1


/* CHECK v.1.1 */
/* getnam  -  Peel off the directory path and extension from the full name
              of the .pdb file */

/* SOURCE OF CODE : PROCHECK package (Roman Laskowski, Oct 13, 1994) */
/* MODIFIED (Ton Rullmann): strips off leading % character */

int getnam(char *pdbfil, int *istart, int *iend)
{
     char pchar;
     int  finish, gotdot, ipos, istate;


/*-- Initialise variables --*/
     finish = FALSE;
     *iend = -1;
     *istart = 0;
     istate = 1;
     ipos = strlen(pdbfil) - 1;
/*
     printf("Starting ipos = %d\n",ipos);
*/
     gotdot = FALSE;

/*-- Check through the filename from right to left --*/
     while (finish == FALSE && ipos > -1)
     {

/*--     Pick off next character --*/
         pchar = pdbfil[ipos];
/*
         printf("ipos=%d, pchar=[%c]  istate=%d\n",ipos,pchar,istate);
*/

/*--     State 1: Searching for first non-blank character --*/
         if (istate == 1)
         {
             if (pchar == '/' || pchar == '\\' || pchar == ']')
             {
                 printf("*** ERROR in supplied name of file: [%s\n",
                    pdbfil);
                 return(-1);
             }

             if (pchar != ' ' && pchar != '.')
             {
                 *iend = ipos;
                 istate = 2;
             }
         }

/*--     State 2: Searching for end of extension, or end of directory path --*/
         else if (istate == 2)
         {

/*--        If character is a dot, and is the first dot, then note position--*/
            if (pchar == '.' && gotdot == FALSE)
            {
                *iend = ipos - 1;
                gotdot = TRUE;
            }

/*--        If character signifies the end of a directory path, note pstn --*/
            else if (pchar == '/' || pchar == '\\' || pchar == ']' || pchar == '%' )
            {
                *istart = ipos + 1;
                finish = TRUE;
            }
        }

/*--    Step back a character --*/
        ipos = ipos - 1;
     }

/*-- Check whether file name is sensible --*/
     if (*istart > *iend)
     {
         printf("*** ERROR in supplied name of file: %s\n", pdbfil);
         printf("    No name found\n");
         return(-1);
     }
     return(0);
}


int main( int argc, char *argv[] )
{
    int    i, istart, iend, ierror;
    char   *name;

    if ( argc <= 1 )
    {
        puts( "usage: getproj file_path_name" );
        exit( 1 );
    }
    name = argv[1];

    ierror = getnam( name, &istart, &iend );
    if ( ierror != -1 )
    {
        for ( i=istart; i<iend+1; i++ )
            putchar( name[i] );
        putchar( '\n' );
    }
}

